package cn.com.yinhex.util; 

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookies {
	HttpServletRequest request = null;
	HttpServletResponse response = null;
	Cookie[] cs = null;

	public Cookies(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.cs = request.getCookies();
	}

	public void addCookie(String name, String value) {
		try {
			Cookie c = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
			c.setPath("/");
			c.setMaxAge(86400 / 2);
			response.addCookie(c);
		} catch (Exception e) {
		}
	}

	public void delCookie(String name) {
		Cookie c = new Cookie(name, "");
		c.setPath("/");
		c.setMaxAge(0);
		response.addCookie(c);
	}

	public void delAllCookie() {
		for (int i = 0; cs != null && i < cs.length; i++) {
			delCookie(cs[i].getName());
		}
	}

	public String getCookie(String name) {
		for (int i = 0; name != null && cs != null && i < cs.length; i++) {
			if (name.equals(cs[i].getName())) {
				try {
					return URLDecoder.decode(cs[i].getValue(), "UTF-8");
				} catch (Exception e) {
				}
			}
		}
		return "";
	}
}
